{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d48af3cf",
   "metadata": {},
   "source": [
    "# 量化神经网络\n",
    "\n",
    "QNN(Quantized Neural Network)算子模块提供了模拟量化和反量化算子的函数，这些函数可以在保持原始数据类型的情况下模拟量化神经网络的行为，支持动态数据类型选择和通道级别的量化参数设置。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "911c8a6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tvm\n",
    "from tvm import te, tir, topi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52d38da2",
   "metadata": {},
   "source": [
    "```python\n",
    "# 量化状态常量定义\n",
    "SQNN_DISABLE = 0  # 禁用量化，直接通过原始值\n",
    "SQNN_INT8 = 1     # 模拟int8量化\n",
    "SQNN_UINT8 = 2    # 模拟uint8量化\n",
    "SQNN_INT32 = 3    # 模拟int32量化\n",
    "\n",
    "# 数据类型字符串到枚举值的映射\n",
    "SQNN_DTYPE_TO_CODE = {\n",
    "    \"disable\": SQNN_DISABLE,\n",
    "    \"int8\": SQNN_INT8,\n",
    "    \"uint8\": SQNN_UINT8,\n",
    "    \"int32\": SQNN_INT32,\n",
    "}\n",
    "\n",
    "# 枚举值到数据类型字符串的反向映射\n",
    "SQNN_CODE_TO_DTYPE = {v: k for k, v in SQNN_DTYPE_TO_CODE.items()}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6353886c",
   "metadata": {},
   "source": [
    "```python\n",
    "@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)  # 标记为逐元素操作，便于优化\n",
    "def simulated_quantize(data, out_dtype, output_scale=None, output_zero_point=None, axis=-1):\n",
    "    \"\"\"\n",
    "    模拟QNN量化操作，在不改变数据类型的情况下模拟量化输出\n",
    "    \n",
    "    此操作相比真实QNN量化的优势在于：\n",
    "    1. 支持动态数据类型选择\n",
    "    2. 可以处理通道级和标量级的scale和zero_point参数\n",
    "    3. 而真实QNN量化要求这些参数在编译时固定\n",
    "    \n",
    "    量化数学公式：\n",
    "    Q_output = clip(round(input_tensor/output_scale) + output_zero_point, out_dtype::min, out_dtype::max)\n",
    "\n",
    "    参数\n",
    "    ----------\n",
    "    data: tvm.te.Tensor\n",
    "        输入张量，可以是任意维度\n",
    "\n",
    "    out_dtype: tvm.te.Tensor\n",
    "        一个标量变量，指示要模拟的量化数据类型。使用SQNN_DTYPE_TO_CODE将字符串转换为对应的值\n",
    "\n",
    "    output_scale: tvm.te.Tensor, optional\n",
    "        用于量化到整数类型的缩放因子张量。\n",
    "        当包含多个值时，N必须与数据中的通道数匹配\n",
    "\n",
    "    output_zero_point: tvm.te.Tensor, optional\n",
    "        用于量化到整数类型的零点张量。\n",
    "        当包含多个值时，N必须与数据中的通道数匹配\n",
    "\n",
    "    axis: int, optional\n",
    "        量化的通道轴。默认值为-1，表示最后一个轴\n",
    "\n",
    "    返回\n",
    "    -------\n",
    "    tvm.te.Tensor\n",
    "        形状与输入相同的张量，包含模拟量化后的值\n",
    "    \"\"\"\n",
    "\n",
    "    # 当禁用量化时，直接返回输入值\n",
    "    def _compute_pass_through(value, *indices):\n",
    "        return value[indices]\n",
    "\n",
    "    # 模拟任意整数类型的量化计算\n",
    "    # 计算式：Q_output = clip(round(input_tensor/output_scale) + output_zero_point, min, max)\n",
    "    def _compute_intn(dtype, value, *indices):\n",
    "        assert output_scale is not None and output_zero_point is not None\n",
    "        const_min = tvm.tir.min_value(dtype)  # 获取目标数据类型的最小值\n",
    "        const_max = tvm.tir.max_value(dtype)  # 获取目标数据类型的最大值\n",
    "        \n",
    "        # 使用indexmod处理标量和通道级的QNN参数\n",
    "        # 当参数是标量时，indexmod确保始终访问第一个元素\n",
    "        scale_idx = tir.indexmod(indices[axis], topi.shape(output_scale)[0])\n",
    "        zp_idx = tir.indexmod(indices[axis], topi.shape(output_zero_point)[0])\n",
    "        \n",
    "        # 执行量化计算：取整 -> 加上零点 -> 裁剪到目标类型范围内\n",
    "        return te.max(\n",
    "            te.min(\n",
    "                te.round(value[indices] / output_scale[scale_idx]) + output_zero_point[zp_idx],\n",
    "                const_max,\n",
    "            ),\n",
    "            const_min,\n",
    "        )\n",
    "\n",
    "    # 使用条件链动态选择适当的量化方法\n",
    "    # 这种设计允许一次编译但使用不同的量化方法，只需要通过变量数据类型输入控制\n",
    "    def _dispatch_sim_quantize(value):\n",
    "        # 创建直通计算（禁用量化时使用）\n",
    "        pass_through_value = te.compute(\n",
    "            data.shape, lambda *indices: _compute_pass_through(value, *indices)\n",
    "        )\n",
    "        \n",
    "        # 处理int8量化\n",
    "        int8_value = te.compute(\n",
    "            data.shape,\n",
    "            lambda *indices: tir.if_then_else(\n",
    "                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"int8\"]),\n",
    "                _compute_intn(\"int8\", value, *indices),\n",
    "                pass_through_value[indices],\n",
    "            ),\n",
    "        )\n",
    "        \n",
    "        # 处理uint8量化\n",
    "        uint8_value = te.compute(\n",
    "            data.shape,\n",
    "            lambda *indices: tir.if_then_else(\n",
    "                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"uint8\"]),\n",
    "                _compute_intn(\"uint8\", value, *indices),\n",
    "                int8_value[indices],\n",
    "            ),\n",
    "        )\n",
    "        \n",
    "        # 处理int32量化\n",
    "        int32_value = te.compute(\n",
    "            data.shape,\n",
    "            lambda *indices: tir.if_then_else(\n",
    "                out_dtype.equal(SQNN_DTYPE_TO_CODE[\"int32\"]),\n",
    "                _compute_intn(\"int32\", value, *indices),\n",
    "                uint8_value[indices],\n",
    "            ),\n",
    "        )\n",
    "\n",
    "        return int32_value\n",
    "\n",
    "    # 构建最终的计算结果\n",
    "    return te.compute(data.shape, lambda *indices: _dispatch_sim_quantize(data)[indices])\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c81fb19d",
   "metadata": {},
   "source": [
    "```python\n",
    "@tvm.te.tag_scope(tag=topi.tag.ELEMWISE)  # 标记为逐元素操作，便于优化\n",
    "def simulated_dequantize(data, in_dtype, input_scale=None, input_zero_point=None, axis=-1):\n",
    "    \"\"\"\n",
    "    模拟QNN反量化操作，在不改变数据类型的情况下模拟反量化输出\n",
    "    \n",
    "    此操作相比真实QNN反量化的优势在于：\n",
    "    1. 支持动态数据类型选择\n",
    "    2. 可以处理通道级和标量级的scale和zero_point参数\n",
    "    3. 而真实QNN反量化要求这些参数在编译时固定\n",
    "    \n",
    "    反量化数学公式：\n",
    "    DQ_output = (input - zero_point) * scale\n",
    "\n",
    "    参数\n",
    "    ----------\n",
    "    data: tvm.te.Tensor\n",
    "        输入张量，可以是任意维度\n",
    "\n",
    "    in_dtype: tvm.te.Tensor\n",
    "        一个标量变量，指示要模拟的反量化数据类型。使用SQNN_DTYPE_TO_CODE将字符串转换为对应的值\n",
    "\n",
    "    input_scale: tvm.te.Tensor, optional\n",
    "        用于从整数类型反量化的缩放因子张量。\n",
    "        当包含多个值时，N必须与数据中的通道数匹配\n",
    "\n",
    "    input_zero_point: tvm.te.Tensor, optional\n",
    "        用于从整数类型反量化的零点张量。\n",
    "        当包含多个值时，N必须与数据中的通道数匹配\n",
    "\n",
    "    axis: int, optional\n",
    "        量化的通道轴。默认值为-1，表示最后一个轴\n",
    "\n",
    "    返回\n",
    "    -------\n",
    "    tvm.te.Tensor\n",
    "        形状与输入相同的张量，包含模拟反量化后的值\n",
    "    \"\"\"\n",
    "\n",
    "    # 当禁用反量化时，直接返回输入张量\n",
    "    def _compute_pass_through(value, *indices):\n",
    "        return value[indices]\n",
    "\n",
    "    # 模拟任意整数类型的反量化计算\n",
    "    # 计算式：DQ_output = (input - zero_point) * scale\n",
    "    def _compute_intn(value, *indices):\n",
    "        assert input_scale is not None and input_zero_point is not None\n",
    "        \n",
    "        # 使用indexmod处理标量和通道级的QNN参数\n",
    "        scale_idx = tir.indexmod(indices[axis], topi.shape(input_scale)[0])\n",
    "        zp_idx = tir.indexmod(indices[axis], topi.shape(input_zero_point)[0])\n",
    "        \n",
    "        # 执行反量化计算：减去零点 -> 乘以缩放因子\n",
    "        return (value[indices] - input_zero_point[zp_idx]) * input_scale[scale_idx]\n",
    "\n",
    "    # 使用条件链动态选择适当的反量化方法\n",
    "    # 这种设计允许一次编译但使用不同的反量化方法，只需要通过变量数据类型输入控制\n",
    "    def _dispatch_sim_dequantize(value):\n",
    "        # 创建直通计算（禁用反量化时使用）\n",
    "        pass_through_value = te.compute(\n",
    "            data.shape, lambda *indices: _compute_pass_through(value, *indices)\n",
    "        )\n",
    "        \n",
    "        # 创建一个条件，检查是否为任意整数类型的量化\n",
    "        intn_condition = tvm.te.any(\n",
    "            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"int8\"]),\n",
    "            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"uint8\"]),\n",
    "            in_dtype.equal(SQNN_DTYPE_TO_CODE[\"int32\"]),\n",
    "        )\n",
    "        \n",
    "        # 根据条件选择是否执行反量化计算\n",
    "        intn_value = te.compute(\n",
    "            data.shape,\n",
    "            lambda *indices: tir.if_then_else(\n",
    "                intn_condition,\n",
    "                _compute_intn(value, *indices),\n",
    "                pass_through_value[indices],\n",
    "            ),\n",
    "        )\n",
    "\n",
    "        return intn_value\n",
    "\n",
    "    # 构建最终的计算结果\n",
    "    return te.compute(data.shape, lambda *indices: _dispatch_sim_dequantize(data)[indices])\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "551382bf",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py313",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
